#ifndef PARALLEL_FOR_HPP_
#define PARALLEL_FOR_HPP_
#include <memory>
#include "ThreadPool.h"
#ifndef DEFAULT_THREADS
#define DEFAULT_THREADS 4  // 默认线程数宏定义
#endif
// 使用unique_ptr管理全局线程池
std::unique_ptr<ThreadPool> init_pool() {
    const char* env_threads = std::getenv("THREAD_NUM");
    size_t threads = env_threads ? std::atoi(env_threads) : DEFAULT_THREADS;
    return std::make_unique<ThreadPool>(threads);
}

ThreadPool& get_pool() {
    static std::unique_ptr<ThreadPool> pool = init_pool();
    return *pool;
}

// parallel_for实现
template<typename Func>
void parallel_for(size_t start, size_t end, Func func) {
    const size_t chunk_size = (end - start) / (get_pool().worker_size() * 2);
    std::vector<std::future<void>> futures;
    
    for(size_t i = start; i < end; ) {
        size_t current_end = std::min(i + chunk_size, end);
        futures.emplace_back(
            get_pool().enqueue([i, current_end, &func] {
                for(size_t j = i; j < current_end; ++j) func(j);
            })
        );
        i = current_end;
    }
    
    for(auto& future : futures) future.wait();
}
#endif